package quick.portal.fragment;

import java.io.IOException;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;
import com.squareup.picasso.Picasso;

import quick.communication.AsyncHttpResponseHandler;
import quick.portal.R;
import quick.portal.activity.MainActivity;
import quick.portal.data.APIResult;
import quick.portal.service.BaseService;
import quick.view.pulltorefresh.PullToRefreshBase;
import quick.view.pulltorefresh.PullToRefreshListView;
import quick.view.quickadapter.BaseAdapterHelper;
import quick.view.quickadapter.QuickAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;

public abstract class DataListFragment<T extends Object> extends Fragment implements OnMenuItemClickListener {
	
	protected static int PAGE_SIZE = 50;
	
	protected Activity context = null;
	protected boolean isLoadAll = false;
	protected int pageIndex = 1;
	
	protected boolean firstRun = true;
	
	protected PullToRefreshListView listView = null;
	protected QuickAdapter<T> adapter = null;
	
	protected String queryAction;
	protected int itemViewLayoutId;
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.data_list_layout, container,false);
		
		this.listView = (PullToRefreshListView)view.findViewById(R.id.data_list);
		
		return view;
	}
	
	protected PopupMenu GetOriginalPopupMenu()
	{
		PopupMenu menu = ((MainActivity)this.getActivity()).getPopupMenu();
		menu.getMenu().add(R.id.menu_group_data,R.id.menu_refresh,menu.getMenu().size(),"刷新数据");
		
		return menu;
	}
	
	@Override
	public boolean onMenuItemClick(MenuItem item) {
		
		((MainActivity)this.getActivity()).menuItemClick(item);
		
		if(item.getItemId() == R.id.menu_refresh)
		{
			this.refreshData();
            return true;
		}
		
		return false;
	}
	
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        this.setHasOptionsMenu(true);
        this.context = getActivity();
        
        this.initView();
    }

	@Override
    public void onResume() {
        super.onResume();
        Picasso.with(context).resumeTag(context);
        
        if(!firstRun)
        {
	        this.refreshData();
        }
        else
        {
        	firstRun = false;
        }
    }
	
    @Override
    public void onPause() {
        super.onPause();
        Picasso.with(context).pauseTag(context);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Picasso.with(context).cancelTag(context);
    }
	
	protected void initData() {
        this.pageIndex = 1;
        this.isLoadAll = false;        
    }
	
	protected abstract void adapterConvert(BaseAdapterHelper helper, T object);
	
	protected abstract void showDetail(View view);
	
	protected abstract List<T> parseArray(String body);
	
	protected void initItemView(View view)
	{
		//
	}
	
	protected void initView() 
	{
		this.firstRun = true;
		
        initData();
        
        this.adapter = new QuickAdapter<T>(context, this.itemViewLayoutId) {
            @Override
            protected void convert(BaseAdapterHelper helper, T object) {
            	adapterConvert(helper,object);
            }

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View view = super.getView(position, convertView, parent);
				
				initItemView(view);
				
				return view;
			}
            
            
        };

        listView.addFooterView();        
        listView.setAdapter(adapter);
        
        // 下拉刷新
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
            	adapter.clear();
                initData();
                loadData();
            }
        });
        
        // 加载更多
        listView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadData();
            }
        });
        
        // 点击事件
        listView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            	showDetail(view);
            }
        });

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                    Picasso.with(context).pauseTag(context);
                } else {
                    Picasso.with(context).resumeTag(context);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });

        loadData();
    }
	
	protected void loadData() 
	{
        if (isLoadAll) {
            return;
        }
        
        this.listView.setFooterViewTextNormal();
        
        new BaseService().List(this.pageIndex, PAGE_SIZE,this.queryAction,new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String body) {

                listView.onRefreshComplete();

                APIResult result = JSON.parseObject(body, APIResult.class);
    			
    			if(result.getReturnCode()<0)
	        	{
					listView.onRefreshComplete();
					listView.setFooterViewTextError();
					return;
	        	}
    			
                List<T> list = parseArray(result.getBody());
                

                // 暂无数据
                if (pageIndex == 1 && list.isEmpty()) {
                    listView.setFooterViewTextNoData();
                    return;
                }

                // 已加载全部
                if (pageIndex >= 1 && (list.isEmpty() || list.size() < PAGE_SIZE)) {
                    listView.setFooterViewTextNoMoreData();
                    isLoadAll = true;
                }

                adapter.addAll(list);
                pageIndex++;
            }

            @Override
            public void onFailure(Request request, IOException e) {
                listView.onRefreshComplete();
                listView.setFooterViewTextError();
            }
        });
    }
	
	protected void refreshData()
	{
		this.adapter.clear();
        this.initData();
        this.loadData();
	}

}
